<script setup lang="tsx">
import { watch, inject, Ref, ref, onBeforeUnmount, onMounted } from 'vue'
import { getListApi } from '@/api/system/menu'
import { Row } from '@/api/system/role'
import { ElForm, ElFormItem, ElInput, ElTree, ElRadioGroup, ElRadio } from 'element-plus'
const currentRow: Ref<Row> = inject('currentRow') as Ref<Row>
const formRef = ref<InstanceType<typeof ElForm>>()
const tree = ref<any>(null)
onMounted(() => {
  currentRow.status = currentRow.status.toString()
  if (currentRow.menu_ids) {
    tree.value.setCheckedKeys(currentRow.menu_ids)
  }

  getListApidata()
})
const options = ref<Array<{ name: string; id: number }>>([])
const getListApidata = async () => {
  const res = await getListApi()
  options.value = res.data.list
}

// 权限
const handleNodeClick = () => {
  currentRow.menu_ids = [...tree.value.getHalfCheckedKeys(), ...tree.value.getCheckedKeys()].join(
    ','
  )
}
// 提交
const submit = async () => {
  const valid = await formRef.value?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    handleNodeClick()
    return currentRow
  }
}
// 重置
const reset = async () => {
  Object.assign(currentRow, {})
}

watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    console.log(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

onBeforeUnmount(reset)

defineExpose({
  submit,
  reset
})
</script>

<template>
  <ElForm ref="formRef" :model="currentRow" label-width="100px">
    <ElFormItem prop="name" label="角色名称" required>
      <ElInput v-model="currentRow.name" placeholder="请输入内容" />
    </ElFormItem>
    <ElFormItem prop="role_key" label="权限字符" required>
      <ElInput v-model="currentRow.role_key" placeholder="请输入内容" />
    </ElFormItem>
    <ElFormItem prop="role_sort" label="显示顺序" required>
      <ElInput v-model="currentRow.role_sort" placeholder="请输入内容" />
    </ElFormItem>
    <ElFormItem label="状态" prop="status">
      <ElRadioGroup v-model="currentRow.status">
        <ElRadio label="1">是</ElRadio>
        <ElRadio label="2">否</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
    <ElFormItem prop="remark" label="备注">
      <ElInput v-model="currentRow.remark" placeholder="请输入内容" />
    </ElFormItem>
    <ElFormItem prop="menu_ids" label="菜单权限">
      <ElTree
        :data="options"
        :defaultExpandAll="true"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        check-strictly
        node-key="id"
        ref="tree"
        @check-change="handleNodeClick"
      />
    </ElFormItem>
  </ElForm>
</template>
